import Vue from 'vue'
import Vuex from 'vuex'
import { login, logout, getUserInfo, getUserPermissions } from "../api/qccx";
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: null, // 用户信息
		menuMap: null,
		buttonMap: null,
	},
	getters:{
		userInfo:(state) => {
			if (!state.userInfo) {
				try {
					const userInfo = uni.getStorageSync('userInfo');
					state.userInfo = userInfo
				} catch (e) {
					console.error(e)
				}
			}
			return state.userInfo
		},
		menuMap:(state) => {
			if (!state.menuMap) {
				try {
					const menuMap = uni.getStorageSync('menuMap');
					state.menuMap = menuMap
				} catch (e) {
					console.error(e)
				}
			}
			return state.menuMap
		},
		buttonMap:(state) => {
			if (!state.buttonMap) {
				try {
					const buttonMap = uni.getStorageSync('buttonMap');
					state.buttonMap = buttonMap
				} catch (e) {
					console.error(e)
				}
			}
			return state.buttonMap
		},
	},
	mutations: {
		SET_USER_INFO(state,userInfo){
			uni.setStorageSync('userInfo', userInfo)
			state.userInfo = userInfo
		},
		SET_MENU_MAP(state,mapInfo){
			uni.setStorageSync('menuMap', mapInfo)
			state.menuMap = mapInfo
		},
		SET_BUTTON_MAP(state,mapInfo){
			uni.setStorageSync('buttonMap', mapInfo)
			state.buttonMap = mapInfo
		},
		CLEAR_USER_INFO(state){
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('menuMap')
			uni.removeStorageSync('buttonMap')
			state.userInfo = null
			state.menuMap = null
			state.buttonMap = null
		},
	},
	actions:{
		LOG_OUT({ commit }){
			return new Promise((resolve, reject) => {
				logout({}).then((res)=>{
					if(res.code==200){
						commit('CLEAR_USER_INFO')
						resolve()
					}else{
						reject(res.resultMsg)
						uni.showToast({title:res.resultMsg?res.resultMsg:'网络异常,请稍后再试',icon:'none'})
					}
				})
			})
		},
		GET_PERMISSION({ commit }){
			return new Promise((resolve, reject) => {
				getUserPermissions().then((res)=>{
					if(res.code==200){
						// 筛选按钮权限
						const result = res.result;
						const resourceList = result.resourceList || [];
						let menuMap = [];
						let buttonMap = [];
						resourceList.forEach((element) => {
							if (element.type == 'MENU') {
								menuMap.push(element.permission);
							}
							if (element.type == 'BUTTON') {
								buttonMap.push(element.permission);
							}
						});
						commit('SET_MENU_MAP', menuMap)
						commit("SET_BUTTON_MAP", buttonMap);
						resolve(menuMap, buttonMap);
					}else{
						reject(res.resultMsg)
						uni.showToast({title:res.resultMsg?res.resultMsg:'网络异常,请稍后再试',icon:'none'})
					}
				}).catch()
			})
		},
	},
})

export default store
